#!/bin/bash
# $1 srart_freq; $2 end_freq; $3 pll1 or pll2
start=0
if (($1));then
start=$1
else
	echo "Please input start frequency!"
fi

if (($2));then
end=$2
else
        echo "Please input end frequency!"
fi

vco_band=0x31d
pll=1
vco_reg=0x31c
if (($3)); then
	if (( $3 > 2 || $3 < 1)); then
		echo "PLL$3 is not exist!"
		exit 0;
	fi
	pll=$3
	if (( $pll == 2 ));then 
		vco_band=0x329
		vco_reg=0x328
	fi
fi

get_sar()
{
	if (( $1 )); then
		vco_band=$1
	else 
		exit 1
	fi
	echo 0x3d0 "$1" > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	echo 0x3e0 > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	sar_pow=$(cat /sys/kernel/debug/iio/iio:device0/direct_reg_access)
	let "sar_pow&=0xd7"
	echo 0x3e0 "$sar_pow" > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	echo 0x3d2 > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	sar_start=$(cat /sys/kernel/debug/iio/iio:device0/direct_reg_access)
	let "sar_start|=0x0c"
	echo 0x3d2 "$sar_start" > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	sar=$(cat /sys/bus/spi/devices/spi0.0/iio:device0/in_voltage2_raw)
	echo "$sar"
}

get_band()
{
	if (( $1 )); then
		vco_band=$1
	else 
		exit 1
	fi
	echo "$vco_band" > /sys/kernel/debug/iio/iio:device0/direct_reg_access
	band=$(cat /sys/kernel/debug/iio/iio:device0/direct_reg_access)
	let "band&=0x3f"
	band=$(printf %d $band)
	echo $band
}

rm scan_freq* > /dev/null 2>&1
i=0
while ((i<1))
do
	echo "freq,sar,band,flag,vco"
	echo "freq,sar,band,flag,vco" >> "scan_freq$i.csv"	
	freq=$start
	while (($freq<$end))
	do
		echo "$freq" > /sys/kernel/debug/iio/iio:device0/avc,retune_pll"$pll"
		echo "$pll" > /sys/kernel/debug/iio/iio:device0/avc,lock_flag_pll
		flag=$(cat /sys/kernel/debug/iio/iio:device0/avc,lock_flag_pll)
		band=`get_band $vco_band`
		sar=`get_sar $pll`
		echo "$vco_reg" > /sys/kernel/debug/iio/iio:device0/direct_reg_access
		vco=$(cat /sys/kernel/debug/iio/iio:device0/direct_reg_access)
		let "vco&=0x60"
		let "vco>>=5"
		vco=$(printf %d $vco)
		echo "$freq,$sar,$band,$flag,$vco"
		echo "$freq,$sar,$band,$flag,$vco" >> "scan_freq$i.csv"	
		let freq=$freq+1000000
	done
	let i=$i+1
done
